<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { $t } from '@/locales';
import { queryMenuPermission, queryPermissionIdsWithRoleId, add } from '@/service/api/system-manage';

defineOptions({ name: 'DhkPermissionDialog' });

// Props
const props = defineProps({
  roleId: {
    type: [Number, String],
    required: true
  },
  visible: {
    type: Boolean,
    default: false
  }
});

// Emits
const emit = defineEmits(['update:visible', 'close', 'success']);

// Dialog visibility
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// Title
const title = computed(() => $t('common.edit') + ' 权限配置');

// Data
const permissionTree = ref([]);
const checkedPermissionIds = ref([]);
const loading = ref(false);
const submitLoading = ref(false);
const fetchError = ref(false);

// Tree config
const defaultProps = {
  children: 'children',
  label: 'title'
};

// Methods
function closeModal() {
  emit('update:visible', false);
  emit('close');
}

async function getPermissionTree() {
  loading.value = true;
  fetchError.value = false;
  
  try {
    const res = await queryMenuPermission();
    if (res?.data) {
      permissionTree.value = Array.isArray(res.data) ? res.data : [res.data];
    } else {
      fetchError.value = true;
    }
  } catch (error) {
    console.error('获取权限菜单树失败:', error);
    window.$message?.error('获取权限菜单树失败');
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

async function getRolePermissionIds() {
  const roleId = Number(props.roleId);
  
  if (!roleId) {
    return;
  }
  
  loading.value = true;
  fetchError.value = false;
  
  try {
    const res = await queryPermissionIdsWithRoleId(roleId);
    if (res?.data) {
      checkedPermissionIds.value = Array.isArray(res.data) 
        ? res.data.map(id => Number(id)).filter(Boolean)
        : [];
    } else {
      fetchError.value = true;
    }
  } catch (error) {
    console.error('获取角色权限IDs失败:', error);
    window.$message?.error('获取角色权限列表失败');
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

function handleCheck(_data, checked) {
  if (checked?.checkedKeys) {
    checkedPermissionIds.value = Array.isArray(checked.checkedKeys)
      ? checked.checkedKeys.map(id => Number(id)).filter(Boolean)
      : [];
  }
}

async function handleSubmit() {
  const roleId = Number(props.roleId);
  
  if (!roleId) {
    window.$message?.warning('请选择角色');
    return;
  }

  submitLoading.value = true;
  
  try {
    const params = {
      roleId,
      permissionIds: checkedPermissionIds.value
    };

    const result = await add(params);
    
    if (result) {
      window.$message?.success('权限更新成功');
      emit('success');
      closeModal();
    } else {
      window.$message?.error('提交失败');
    }
  } catch (error) {
    console.error('提交权限配置失败:', error);
    window.$message?.error('提交失败');
  } finally {
    submitLoading.value = false;
  }
}

function init() {
  checkedPermissionIds.value = [];
  permissionTree.value = [];
  fetchError.value = false;
  
  getPermissionTree();
  getRolePermissionIds();
}

// Watchers
watch(() => props.visible, (newVal) => {
  if (newVal) {
    init();
  }
});

watch(() => props.roleId, (newVal, oldVal) => {
  if (props.visible && newVal !== oldVal) {
    init();
  }
});

// Init
onMounted(() => {
  if (props.visible) {
    init();
  }
});
</script>

<template>
  <div class="permission-dialog">
    <el-dialog 
      v-model="dialogVisible" 
      :title="title" 
      width="600px" 
      destroy-on-close
      @closed="closeModal"
    >
      <div v-loading="loading" class="h-400px overflow-auto">
        <div v-if="fetchError" class="flex-center h-full">
          <el-result
            icon="error"
            title="操作失败"
            sub-title="获取权限数据失败，请刷新重试"
          >
            <template #extra>
              <el-button type="primary" @click="init">重新加载</el-button>
            </template>
          </el-result>
        </div>
        <el-tree
          v-else
          node-key="id"
          :data="permissionTree"
          :props="defaultProps"
          :default-checked-keys="checkedPermissionIds"
          :default-expanded-keys="checkedPermissionIds"
          show-checkbox
          @check="handleCheck"
        />
      </div>
      <template #footer>
        <div class="w-full d-flex justify-end">
          <el-button @click="closeModal">{{ $t('common.cancel') }}</el-button>
          <el-button 
            type="primary" 
            :loading="submitLoading" 
            @click="handleSubmit"
          >
            {{ $t('common.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.h-400px {
  height: 400px;
}
.h-full {
  height: 100%;
}
.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
.w-full {
  width: 100%;
}
.d-flex {
  display: flex;
}
.justify-end {
  justify-content: flex-end;
}
</style> 